﻿
Public Class frmMain
    Public pbn As New PhotobucketNet.Photobucket("149829161", "0c6019dd0e054a4fd7d6bcd0e762b7d8")
    Public ftpService As New OpenServers.Net.FtpServer.FtpServer
    Public UserToken As New PhotobucketNet.UserToken
    Public lastfile As String
    Public WatchFolder As String = My.Computer.FileSystem.SpecialDirectories.Temp
    Public ftpPort As Integer = FtpServer.DEFAULT_NONSECURE_PORT

    Private Sub cmdRequestToken_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRequestToken.Click
        pbn.LaunchUserLogin()

        cmdRequestToken.Enabled = False

        Dim msgValidate As New MsgBoxResult
        msgValidate = MsgBox("You will be directed to a PhotoBucket login page. " + Chr(10) + Chr(13) + "Please click OK once you have logged in successfully.", MsgBoxStyle.OkCancel, "Please authorise this app:")

        If MsgBoxResult.Ok = 1 Then
            Try
                pbn.RequestUserToken()

                lblLoggedInStatus.Text = "Logged in: " + pbn.UserToken.Username
            Catch ex As Exception
                cmdRequestToken.Enabled = True
                lblLoggedInStatus.Text = "Failed to authenticate"
                MsgBox("Could not validate token returned:" + ex.Message, MsgBoxStyle.Exclamation, "Failed to authenticate:")
            End Try
        End If

    End Sub

Public Sub New()

        InitializeComponent()

        Try
            LoginUser()
        Catch ex As Exception
            cmdRequestToken.Enabled = True
        End Try

        txtWatchFolder.Text = WatchFolder
        fswFileWatch.Path = WatchFolder
        txtFTPPort.Value = ftpPort

End Sub

Public Sub LoginUser()
    Try
        UserToken.Token = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "Token", "").ToString
        UserToken.TokenSecret = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "TokenSecret", "")
        UserToken.Username = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "Username", "")
        UserToken.UserHomeUrl = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "UserHomeUrl", "")
        UserToken.Subdomain = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "Subdomain", "")
        WatchFolder = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "WatchFolder", "")
        ftpPort = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "ftpPort", "21")
        cmdRequestToken.Enabled = False

        pbn.UserToken = UserToken

        lblLoggedInStatus.Text = "Logged in: " + pbn.UserToken.Username
    Catch ex As Exception
        lblLoggedInStatus.Text = "Not logged in"
        cmdRequestToken.Enabled = True
    End Try
End Sub

Private Sub frmMain_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
    ftpService.Stop()

    Try
        My.Computer.Registry.CurrentUser.CreateSubKey("Software\SendToPhotoBucket")
        My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "Token", pbn.UserToken.Token)
        My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "TokenSecret", pbn.UserToken.TokenSecret)
        My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "Username", pbn.UserToken.Username)
        My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "UserHomeUrl", pbn.UserToken.UserHomeUrl)
        My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "Subdomain", pbn.UserToken.Subdomain)
        My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "WatchFolder", WatchFolder)
        My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SendToPhotoBucket", "ftpPort", ftpPort.ToString)
    Catch ex As Exception
        MsgBox("Could not save user information to registry: " + ex.Message.ToString, MsgBoxStyle.Exclamation, "Save failed")
    End Try

End Sub

Private Sub fswFileWatch_Changed(ByVal sender As System.Object, ByVal e As System.IO.FileSystemEventArgs) Handles fswFileWatch.Created

    If e.FullPath <> lastfile Then
        lblCurrentAction.Text = "Uploading: " + e.Name.ToString
        lblCurrentAction.Text = "Waiting..."
        Dim i As Integer = 0

            While My.Computer.FileSystem.GetFileInfo(e.FullPath).LastWriteTime > Now.AddSeconds(-5) And i < 25
                lblCurrentAction.Text += "."
                i += 1
                Delay(1)
            End While

        If i = 25 Then
            lblCurrentAction.Text = "Timed out waiting for file"
        Else

            lblCurrentAction.Text = "Uploading: " + e.Name.ToString

            Try
                Dim mi As New PhotobucketNet.MediaItem(pbn.Username, e.Name, System.IO.File.Open(e.FullPath, IO.FileMode.Open, IO.FileAccess.Read), PhotobucketNet.MediaType.Image)
                pbn.UploadMediaItemToBaseAlbum(mi)
            Catch ex As Exception
                lblCurrentAction.Text = "Failed: " + ex.Message
                Return
            End Try

            lstHistory.Items.Insert(0, lblCurrentAction.Text)
                lastfile = e.FullPath

                If chkDelAfterUp.Checked Then
                    My.Computer.FileSystem.DeleteFile(e.FullPath)
                End If
        End If
        lblCurrentAction.Text = "Waiting..."
    End If
End Sub

    Private Sub chkFTPEnable_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkFTPEnable.CheckedChanged
        If chkFTPEnable.Checked = True Then
            ftpService.Listeners.Add(New NonsecureTcpListener(ftpPort))
            ftpService.FileSystem = New DiskFileSystem(WatchFolder)
            ftpService.SecurityProvider = New OpenSecurityProvider()
            Try
                ftpService.Start()
            Catch ex As Exception
                lstHistory.Items.Insert(0, "FTP Service unable to start")
                MsgBox("FTP Service unable to start:" + ex.Message, MsgBoxStyle.Exclamation, "FTP Start failed:")
                chkFTPEnable.Checked = False
                Return
            End Try
            lstHistory.Items.Insert(0, "FTP Service started")
            lstHistory.Items.Insert(0, "Running on port: " + ftpPort.ToString)
        Else
            ftpService.Stop()
            ftpService.Listeners.Clear()
            lstHistory.Items.Insert(0, "FTP Service stopped")
        End If

    End Sub

Private Sub cmdSelectFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSelectFolder.Click
    fbdFolderBrowser.SelectedPath = WatchFolder
    fbdFolderBrowser.ShowDialog()
    WatchFolder = fbdFolderBrowser.SelectedPath
    txtWatchFolder.Text = WatchFolder
    fswFileWatch.Path = WatchFolder
End Sub

Sub Delay(ByVal dblSecs As Double)

    Const OneSec As Double = 1.0# / (1440.0# * 60.0#)
    Dim dblWaitTil As Date
    Now.AddSeconds(OneSec)
    dblWaitTil = Now.AddSeconds(OneSec).AddSeconds(dblSecs)
    Do Until Now > dblWaitTil
        Application.DoEvents() ' Allow windows messages to be processed
    Loop

End Sub

Private Sub lnkAbout_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkAbout.LinkClicked
    AboutBox.Show()
    End Sub

    Private Sub txtFTPPort_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtFTPPort.LostFocus
        ftpPort = txtFTPPort.Value
    End Sub

    Private Sub chkEnableFileWatch_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkEnableFileWatch.CheckedChanged
        If chkEnableFileWatch.Checked = True Then
            fswFileWatch.NotifyFilter = (System.IO.NotifyFilters.LastAccess Or System.IO.NotifyFilters.LastWrite Or System.IO.NotifyFilters.FileName Or System.IO.NotifyFilters.DirectoryName)
            AddHandler fswFileWatch.Created, AddressOf fswFileWatch_Changed
            fswFileWatch.EnableRaisingEvents = True
            lstHistory.Items.Insert(0, "Watching folder:" + WatchFolder)
        Else
            RemoveHandler fswFileWatch.Created, AddressOf fswFileWatch_Changed
            fswFileWatch.EnableRaisingEvents = False
            lstHistory.Items.Insert(0, "Stopped watching folder")
        End If
    End Sub
End Class